package name.swingeet.attach;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.lang.instrument.Instrumentation;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.rmi.AccessException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.Vector;

import name.swingeet.swingElf.SwingTestImpl;
import name.swingeet.swingElf.SwingTestInterface;


public class SwingAgentRMI {

	public static int DEFAULT_PORT = 1099;

	private SwingTestImpl attachAgent = new SwingTestImpl();

	String agentName = "Swingeet";
	public static void agentmain(String agentArgs, Instrumentation ins) {
		try {
			PrintStream   ps   =   new   PrintStream("agentoutput.txt");
			System.setOut(ps); 
			System.setErr(ps); 
		} catch (Exception e) {
		
			e.printStackTrace();
			
		} 
		SwingAgentRMI sar = new SwingAgentRMI();
		sar.registerToRegistry(DEFAULT_PORT);
	}
	
	private void registerToRegistry(int port) {

		
		Registry registry = null;
		boolean portNotInUse=true;
		try {
			registry = LocateRegistry.createRegistry(port);
		} catch (RemoteException re) {
			portNotInUse=false;;
			re.printStackTrace();

		}
		

		if(portNotInUse){
		try {
			SwingTestInterface stub = (SwingTestInterface) UnicastRemoteObject
					.exportObject(this.attachAgent, 0);
			registry.bind(this.agentName, stub);
			
		} catch (AccessException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (AlreadyBoundException e) {
			e.printStackTrace();
		}
		System.out.println("register successed");
		}

	}

	public static void main(String agentArgs[]) {
		SwingAgentRMI.agentmain(null, null);

	}
}
